package com.summer.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class CountDownLatchTest {
	
	private AtomicInteger counter = new AtomicInteger(0);
//	private int counter = 0;
	
	public static void main(String[] args) {
		CountDownLatchTest test = new CountDownLatchTest();
		CountDownLatch latch = new CountDownLatch(5);
		WaitTask waitTask = test.new WaitTask(latch);
		ConditionsTask conditionsTask1 = test.new ConditionsTask(latch);
		ConditionsTask conditionsTask2 = test.new ConditionsTask(latch);
		ConditionsTask conditionsTask3 = test.new ConditionsTask(latch);
		ConditionsTask conditionsTask4 = test.new ConditionsTask(latch);
		ConditionsTask conditionsTask5 = test.new ConditionsTask(latch);
		
		waitTask.start();
		conditionsTask1.start();
		conditionsTask2.start();
		conditionsTask3.start();
		conditionsTask4.start();
		conditionsTask5.start();
		long time = System.currentTimeMillis();
		for(int index = 0;index<=50000000;index++){
			index++;
		}
		time = System.currentTimeMillis() - time;
		System.out.println("index++:"+time);
	}
	
	public class WaitTask extends Thread{
		CountDownLatch latch ;
		public WaitTask(CountDownLatch latch){
			this.latch = latch;
		}
		@Override
		public void run() {
			try {
				long time = System.currentTimeMillis();
				latch.await();
				System.out.println(counter);
				time = System.currentTimeMillis() - time;

				System.out.println("WaitTask use:"+time);
			} catch (InterruptedException e) { 
				e.printStackTrace();
			}
			
		}
	}
	
	public class ConditionsTask extends Thread{
		CountDownLatch latch ;
		public ConditionsTask(CountDownLatch latch){
			this.latch = latch;
		}
//		@Override
//		public void run() {
//			int index = 0;
//			while(index < 10000000){
//				index++;
////				latch.countDown();
////				if(latch.getCount()<=0){
////					System.out.println(Thread.currentThread().getName()+":"+index);
////					break;
////				}
//				counter.incrementAndGet();
//			}
//			latch.countDown();
//		}
		
		@Override
		public void run() {
			int index = 10000000;
			int tmp = 0;
			while(index > 0){
				index--;
				tmp++;
//				synchronized(latch){
//					for(int i=0;i<10000;i++){
//						index--;
//						counter++;
//					}
//				}
			}
			counter.addAndGet(tmp);
			System.out.println(Thread.currentThread().getName()+":"+index);
			latch.countDown();
		}
	}
	
}
